<?php
namespace App\Libraries;

use App\Exceptions\ApiException;
use App\Jobs\GroupSendPush;
use App\Models\ClientUser;
use Illuminate\Support\Facades\DB;
use JPush\Client;
use JPush\Exceptions\APIConnectionException;
use function Symfony\Component\VarDumper\Tests\Fixtures\bar;

class GroupPush {
	protected $appkey;
	protected $secret;
	protected $client;
	
	public function __construct(){
	
	}
	
	/**
	 * @param $uid
	 * @param $title
	 * @param $content
      *
	 * @param $extra
	 * @return bool
	 * 同步发送
	 */
	public function send(array $array=[]){
		$status = $this->_send($array);
		return $status;
	}
	
	/**
	 * @param $uid
	 * @param $title
	 * @param $content
	 * @param $extra
	 * @return bool
	 * 异步发送推送
	 */
	public function queue(array $array = []){
		$job = (new GroupSendPush($array))->onQueue('send_push');
		dispatch($job);
		return true;
	}
	
	public function _send(array $array){
		// 发送站内信

          $messages_id = DB::table('client_user_messages')->insertGetId($array);
		  $message_type = DB::table('client_user_messages_type')->where(['id'=>$array['type_id']])->first();
          $contents = DB::table('client_user_messages_content')->where(['id'=>$array['content_id']])->first();

		$extras = ['type'=>'messages','messages_id'=>$messages_id ?? 0];
		// 判断是业主还是管家，是不同的秘钥
		$type = ClientUser::where(['id'=>$array['uid']])->value('type');
		switch ($type){
			case 1 :
			case 3 :
				$this->appkey = '611658e4112ec0e6d4794f5c';
				$this->secret = '83639789b5b53fdd86a84300';
				break;
			case 2 :
				$this->appkey = 'fd9349337296579dd56ce666';
				$this->secret = 'c0ded20de140f8756911f8af';
				break;
			case 4:
				$this->appkey = '91fa17d2440ca9a4f4e4c32a';
				$this->secret = '97b17c72876afef9323346be';
				break;
			default :
				logger($array['uid'].'不支持的用户类型，不推送');
				return true;
		}
		$online = (env('APP_ENV') == 'online' ? true : false);
		$client = new Client($this->appkey,$this->secret,'./group_push.txt');
		$this->client = $client->push()->setPlatform('all');
		try{
			$this->client->addTag($array['uid'])->setNotificationAlert($message_type->name)
				->iosNotification($message_type->name.':'.$contents->title,[
					'extras' => $extras,
				])
				->androidNotification($message_type->name.':'.$contents->title,[
					'extras' => $extras,
				])
				->options([
					'apns_production'	=> true 		// True 表示推送生产环境，False 表示要推送开发环境，要等IOS在 appstore 上线，暂写死为false
				])
				->send();
		}catch(APIConnectionException $e){
			logger($array['uid'].'推送失败，错误信息：'.$e->getMessage());
			return false;
		}
		return true;
	}
}